var randomUtils = require ('./randomUtils');
var swipeUtils = require ('./swipeUtils');
var logUtils = require ('./logUtils');
var configUtils = require ('./configUtils');
var ocrCharMap = require ('./ocrCharMap');
var http$ = configUtils.getConfig ('log', 'http', false);

if (!requestScreenCapture ()) {
  toastLog ('请求截图权限失败');
  exit ();
}
function toArray (arrLike) {
  var array = [];
  for (var index = 0; index < arrLike.length; index++) {
    array.push (arrLike[index]);
  }
  return array;
}
function getCaptureImg () {
  var startTime = Date.now ();
  var showing = console.showing;
  if (http$) {
    if (showing) {
      console.hide ();
      sleep (0.1 * 1000);
    }
  }
  var captureImg = captureScreen ();
  if (http$) {
    if (showing) {
      console.show ();
    }
  }
  if (!captureImg) {
    toastLog ('截图失败');
  }
  var endTime = Date.now ();
  var hasExec = (endTime - startTime) / 1000;
  if (hasExec > 1) {
    logUtils.info ('GCI: 截图耗费-' + hasExec + '-s');
  }
  return captureImg;
}
function getOcrResults () {
  var captureImg = getCaptureImg ();
  var ocrResults = toArray (gmlkit.ocr (captureImg, 'zh').toArray (3));
  setTimeout (() => {
    captureImg.recycle ();
  });
  return ocrResults;
}
module.exports = {
  getRegExpConfig (content) {
    var regExpStr = content
      .split ('')
      .map (function (item) {
        var match = ocrCharMap[item];
        var piece = match
          ? '[' + match.concat (item).join ('') + ']+'
          : '[' + item + ']+';
        return piece + `\\s*`;
      })
      .join ('');
    return {
      text: content,
      regExp: new RegExp (regExpStr, 'gi'),
    };
  },
  captureAndLog () {
    var ocrResults = getOcrResults ();
    this.logOcrResults (ocrResults);
  },
  logOcrResults (ocrResults) {
    logUtils.info (
      'LOR:',
      '\n',
      ocrResults.map (item => item.text).join ('\n')
    );
  },
  ocrResultsExist (ocrResults, regExpConfig) {
    for (var index = 0; index < ocrResults.length; index++) {
      var ocrResult = ocrResults[index];
      if (regExpConfig.regExp.test (ocrResult.text)) {
        return ocrResult;
      }
    }
    return false;
  },
  regExpConfigExist (ocrResults, regExpConfigs) {
    for (var index = 0; index < ocrResults.length; index++) {
      var ocrResult = ocrResults[index];
      for (var index2 = 0; index2 < regExpConfigs.length; index2++) {
        var regExpConfig = regExpConfigs[index2];
        if (regExpConfig.regExp.test (ocrResult.text)) {
          return ocrResult;
        }
      }
    }
    return false;
  },
  regExpConfigExistSome (ocrResults, regExpConfigs) {
    var results = [];
    for (var index = 0; index < ocrResults.length; index++) {
      var ocrResult = ocrResults[index];
      for (var index2 = 0; index2 < regExpConfigs.length; index2++) {
        var regExpConfig = regExpConfigs[index2];
        if (regExpConfig.regExp.test (ocrResult.text)) {
          results.push (ocrResult);
        }
      }
    }
    return results;
  },
  captureExistsText (content, logOcrResults, ignoreLog) {
    var regExpConfig = this.getRegExpConfig (content);
    var ocrResults = getOcrResults ();
    var ocrResult = this.ocrResultsExist (ocrResults, regExpConfig);
    if (ocrResult) {
      if (!ignoreLog) {
        logUtils.info ('CET:', '找到', regExpConfig.text, '/', ocrResult.text);
      }
      return ocrResult;
    } else {
      if (logOcrResults) {
        this.logOcrResults (ocrResults);
      }
      return false;
    }
  },
  captureExistsOneText (contents, logOcrResults, ignoreLog) {
    if (!Array.isArray (contents)) {
      contents = [contents];
    }
    var ocrResults = getOcrResults ();
    var regExpConfigs = contents.map (content =>
      this.getRegExpConfig (content)
    );
    var ocrResult = this.regExpConfigExist (ocrResults, regExpConfigs);
    if (ocrResult) {
      if (!ignoreLog) {
        logUtils.info ('CEOT:', '找到', contents.join (','), '/', ocrResult.text);
      }
      return ocrResult;
    } else {
      logUtils.info ('CEOT:', '没找到', contents.join (','));
      if (logOcrResults) {
        this.logOcrResults (ocrResults);
      }
      return false;
    }
  },
  captureExistsSomeText (contents, logOcrResults, ignoreLog) {
    if (!Array.isArray (contents)) {
      contents = [contents];
    }
    var ocrResults = getOcrResults ();
    var regExpConfigs = contents.map (content =>
      this.getRegExpConfig (content)
    );
    var results = this.regExpConfigExistSome (ocrResults, regExpConfigs);
    if (results.length > 0) {
      if (!ignoreLog) {
        logUtils.info (
          'CEOT:',
          '找到',
          contents.join (','),
          '/',
          results.map (item => item.text).join (',')
        );
      }
      return results;
    } else {
      logUtils.info ('CEOT:', '没找到', contents.join (','));
      if (logOcrResults) {
        this.logOcrResults (ocrResults);
      }
      return false;
    }
  },

  captureExistsAllText (contents, logOcrResults, ignoreLog) {
    if (!Array.isArray (contents)) {
      contents = [contents];
    }
    var ocrResults = getOcrResults ();
    var regExpConfigs = contents.map (content =>
      this.getRegExpConfig (content)
    );
    var findResults = [];
    for (var index = 0; index < regExpConfigs.length; index++) {
      var regExpConfig = regExpConfigs[index];
      var ocrResult = this.ocrResultsExist (ocrResults, regExpConfig);
      if (ocrResult) {
        findResults.push (ocrResult);
      }
    }
    if (findResults.length == contents.length) {
      if (!ignoreLog) {
        logUtils.info (
          'CEAT:',
          '找到',
          '\n',
          contents.join (','),
          '\n',
          findResults.map (item => item.text).join (',')
        );
      }
      return true;
    } else {
      logUtils.info ('CEAT:', '没找到', contents.join (','));
      if (logOcrResults) {
        this.logOcrResults (ocrResults);
      }
      return false;
    }
  },
  scrollAndFindSome (contents, logOcrResults, ignoreLog, maxScrollCount) {
    maxScrollCount = maxScrollCount || 10;
    for (var index = 0; index < maxScrollCount; index++) {
      var results = this.captureExistsSomeText (
        contents,
        logOcrResults,
        ignoreLog
      );
      if (results.length > 0) {
        return results;
      }
      sleep (randomUtils.getRandom (1.5, 2, 1000));
      swipeUtils.swipeUp ();
    }
    return [];
  },
};
